<div class="suggest row">
  <div class="sugges-header medium-12 column">
	  <div class="medium-10 medium-centered column" style="padding:0;">
	  	<ul class="inline-list">
	  		<li><a class="on">Suggest Edits</a></li>
	  		<li><a>Edit History</a></li>
	  	</ul>
	  </div>
  </div>

  <div class="medium-10 medium-centered column" style="padding:0;">
  	<div style="height:95%;">
	<div class="medium-5 column">
		<div class="medium-12 column" style="padding:0;margin-top:1rem;">
			<div data-alert class="alert-box secondary" style="border:dashed 1px !important;">
				Review other users' suggestions by marking them as correct or incorrect, or add any information that seems to be missing about this company.
 				<a href="#" class="close">&times;</a>
			</div>
		</div>

		<div class="suggest-card medium-12 column">
			<div class="text-center medium-2 column"  style="padding:0;">
				<a class="radius th">
					<img src="img/user_dp/symb.jpg">
				</a>
			</div>
			<div class="medium-10 column" style="padding:0;">
				<strong>Remote Staff Inc.</strong>
				<div class="suggest-content">
					<label>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
					tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
					quis nostrud exercitation ullamco.Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
					tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
					quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
					consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
					cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
					proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
					</label>					
				</div>
			</div>
		</div>

		<div class="medium-12 column" style="padding:0;">
			<textarea placeholder="Place your Description here..." style="height:15rem;"></textarea>
		</div>
	</div>

	<div class="map medium-7 column">
		<div>
		<input type="text" id="address" placeholder="Type Address" onClick="cleartext();">
	    </div> 

		<div id="map-canvas" class="map-canvas medium-12 column"></div>

		<div class="small-6 columns" style="opacity:0;">
		<input id="latlng" type="text" onfocus="codeLatLng()" onchange="codeLatLng()" size=30 readonly>
		<input id="string" type="text" size=30 readonly>
		</div>
		<div class="small-6 columns" style="opacity:0;">
		<input id="region" type="text" size=30 readonly>
		<input id="city" type="text" size=30 readonly>
		</div>
    </div>
</div>
  
	<div class="saveopt medium-12 column">
		<a class="right radius tiny button">Save</a>
	</div>
  </div>
</div>

<script src="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<script>
var geocoder;
var map;
var autocomplete;
var markers = [];
function initialize(map_id) {
        document.getElementById("latlng").value="<?=$address->long.','.$address->lat ?>";
	    document.getElementById("address").value="<?=$address->address ?>";
	    document.getElementById("string").value="<?=$address->google_add ?>";
	    document.getElementById("city").value="<?=$address->city ?>";
	    document.getElementById("region").value="<?=$address->region ?>";
		  // Create an array of styles.
		var styles = [
				{stylers: [{ hue: "#006652" },{ saturation: -20 }]},
				{featureType: "road", elementType: "geometry",stylers:[{ lightness: 30 },{ visibility: "simplified" }] },
				{featureType: "road",elementType: "labels"}
			   ];
		var styledMap = new google.maps.StyledMapType(styles,{name: "Styled Map"});
		var myLatlng = new google.maps.LatLng(14.586902, 120.98570599999994);
		var mapOptions = {zoom: 15,center: myLatlng, mapTypeControlOptions: {
					mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
		       }};

		 geocoder = new google.maps.Geocoder();
		map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
		map.mapTypes.set('map_style', styledMap);
		map.setMapTypeId('map_style');
		//Search Box location restriction       
		var input = document.getElementById('address');
		var options = {
		componentRestrictions: { country: 'ph' }
		};
		//Autocomplete function
		autocomplete = new google.maps.places.Autocomplete(input, options);
		google.maps.event.addListener(autocomplete, 'place_changed', function() {
		codeAddress(); 
		});

/* Zablan paayos na lng ako dito eto yung logic na para mag default position lng ang mapa kung null pa yung address

 if (<?=$address->address ?> != null) {
	codeaddress();
 }
 else {
	*do nothing
 }

 **Ibig sabihin nyan tatawagin nya lng yung codeAddress() na magcoconvert ng address to coordinates pag may laman lng yung "address"
 pero kung wala  magseset na lng yan sa default coordinates ng mapa yan yung logic dyan.

 Sample lng yang codes di ko alam pag query mo eh.
*/
		}

function codeAddress(AddressToPoints) {
	  var iconBase = 'behomebased-ph/Design/Final/Photos/Icon';
       var address = document.getElementById("address").value;
	   geocoder.geocode( { 'address': address, 'componentRestrictions':{'country':'ph'}}, function(results, status) {

	      if (status == google.maps.GeocoderStatus.OK) {
	        map.setCenter(results[0].geometry.location);
	        var marker = new google.maps.Marker({
	            map: map,
	            icon: URL + 'img/icons/Marker.png',
	            position: results[0].geometry.location,
	            draggable:true,
	        });

        markers.push(marker);

        var coordinates = marker.getPosition();
        coordinates1 = coordinates.toString();
        coordinates2 = coordinates1.substring(1, coordinates1.length-1);
        document.getElementById("latlng").value = coordinates2; 
        document.getElementById("latlng").focus();    
      
        google.maps.event.addListener(marker, 'dragend', function() {
        var coordinates = marker.getPosition();
        coordinates1 = coordinates.toString();
        coordinates2 = coordinates1.substring(1, coordinates1.length-1);
        document.getElementById("latlng").value = coordinates2;  
        document.getElementById("latlng").focus();
        map.setCenter(coordinates);   

        setTimeout(get, 230);

        function get(){
            document.getElementById('address').value = document.getElementById('string').value;
            }
          setTimeout(get, 230);
      });

      } else {
        alert('Geocode was not successful for the following reason: ' + status);
      }

    });

  }
function setAllMap(map) {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(map);
    }
  }
  // Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
    setAllMap(null);
  }
function deleteMarkers() {
    clearMarkers();
    markers = [];
  }

function codeLatLng(PointsToAdress) {
    var input = document.getElementById('latlng').value;
    var latlngStr = input.split(',', 2);
    var lat = parseFloat(latlngStr[0]);
    var lng = parseFloat(latlngStr[1]);
    var latlng = new google.maps.LatLng(lat, lng);
    var string;
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {

          for (var j=0; j<results.length; j++)
          {

          for (var i=0; i<results[j].address_components.length; i++)
              {
                  if (results[j].address_components[i].types[0] == "locality") {
                          //this is the object you are looking for
                          city = results[j].address_components[i];
                      }
                  if (results[j].address_components[i].types[0] == "administrative_area_level_1") {
                          //this is the object you are looking for
                          region = results[j].address_components[i];
                      }
              }
            }

      string = (results[0].formatted_address);
      document.getElementById("string").value = string;
      document.getElementById("city").value =  city.long_name;
      document.getElementById("region").value =  region.long_name;

       if (document.getElementById("region").value == "Metro Manila")
       {
        (document.getElementById("region").value = "National Capital Region");
       }

      var city_name = city.long_name;
      var length = city_name.length;

      if (city_name.substr(-4, 4) == "City")
          {
            document.getElementById("city").value = city_name.substr(0, length-5);
          }

          else if (city_name.substr(0,7) == "City of")
            {
            document.getElementById("city").value = city_name.substr(8,length);
            }
            
             else 
             { 

             }

        } else {
          alert('No results found');
        }
      
      } else {
       
      }

    });
  }

 function cleartext(){
    document.getElementById("address").value="";
    document.getElementById("latlng").value="";
    document.getElementById("string").value="";
    document.getElementById("city").value="";
    document.getElementById("region").value="";
    deleteMarkers();
  }
  google.maps.event.addDomListener(window, 'load', initialize);

</script>

<script type="text/javascript">
	$(function(){

		function followCompany(company_id)
		{
			var params = {};
			params.company_id = company_id;
			return $.ajax({
				url: URL + 'reviews/follow',
				type: 'post',
				data: params,
				dataType: 'json'
			});	
		}
		function UnfollowCompany(company_id)
		{
			var params = {};
			params.company_id = company_id;
			return $.ajax({
				url: URL + 'reviews/unfollow',
				type: 'post',
				data: params,
				dataType: 'json'
			});	
		}
		function addToList(data)
		{
			var container = $('#reviewContainer');
			var template = $('#reviewsTpl').html();
			var html = Mustache.to_html(template,data);
			$(html).prependTo('#reviewContainer').hide().fadeIn('slow');
			jQuery("abbr.timeago").timeago();

				$('.user-rating').jRating({
			  		isDisabled : true,
					type:'small',
					length : 5,
					decimalLength : 1,
				});
		}
		function addReview(rate,reviews,company_id){
			var params = {};
			params.rate = rate;
			params.reviews = reviews;
			params.company_id = company_id;

			return $.ajax({
				url: URL + 'reviews/create',
				type: 'post',
				dataType: 'json',
				data: params
			});
		}

		var $txtReview = $('.txtReview');
		var $txtYourReview = $('.txtYourReview');
		var $btnSaveReview = $('.btnSaveReview');
		var $btnFollow = $('.btnFollowCompany');

		$(document).ready(function(){
			jQuery("abbr.timeago").timeago();
			$(document).on('click','.btnPostReview',function(){
				var review = $txtReview.val();
				$('#txtYourReview').val('');

				$("#reviewRating").jRating({
				  isDisabled : false,
				  step:true,
				  length : 5,
				  canRateAgain : true,
				  nbRates : 10
				});
			
			});
			
			$(document).on('click','.btnFollowCompany',function(){
				
				if($(this).html() != 'Follow'){
					return false;
				}
				var company_id = $(this).attr('company_id');
			
				$(this).html("Processing <img src='<?=BASE_URI?>img/loading2.gif'/>");
				var curr = $(this);
				followCompany(company_id).done(function(result){
				
					if(result.status){
						curr.removeClass('btnFollowCompany').addClass('btnUnFollowCompany').html('Unfollow');
					}else{
						alert("There is a problem saving your request");
					}
				});
			

			});
			$(document).on('click','.btnUnFollowCompany',function(){
				
				if($(this).html() != 'Unfollow'){
					return false;
				}
				var company_id = $(this).attr('company_id');
			
				$(this).html("Processing <img src='<?=BASE_URI?>img/loading2.gif'/>");
				var curr = $(this);
				UnfollowCompany(company_id).done(function(result){
				

					if(result.status){
						curr.removeClass('btnUnFollowCompany').addClass('btnFollowCompany').html('Follow');
					}else{
						alert("There is a problem saving your request");
					}
				});
			
			});
			
			$(document).on('click','.btnSaveReview',function(){
				var rate = $('#txtRate').val();
				var review = $('#txtYourReview').val()
				var company_id = $('#company_id').val();
				$(this).html('<span id="uploading"><img src="<?= BASE_URI ?>img/loading2.gif"/> Processing  </span>');
				addReview(rate,review,company_id).done(function(result){
					if(result.status == true)
					{
						addToList(result.data);
						$('.btnSaveReview').html('Your review has been sent');
						$('#reviewmodal').foundation('reveal', 'close');
					}
					else
					{
						alert(result.messages);
					}
					$('.btnSaveReview').html('Save');
					$('#txtRate').val('');
					$('#txtYourReview').val('');
				});
			});

			var pusher = new Pusher(PUSHER_APP_KEY);
			var channel = pusher.subscribe('company-channel');
			
			channel.bind('added-review', function(data) {
				if(SS_USER_ID != data.user_id){
					addToList(data);
				}
			});
		});
	});

</script>

<script>
	var fixmeTop = $('.suggest').offset().top;       // get initial position of the element

	$(window).scroll(function() {                  // assign scroll event listener

	    var currentScroll = $(window).scrollTop(); // get current position

	    if (currentScroll >= fixmeTop) {           // apply position: fixed if you
	        $('.suggest').css({                      // scroll to that element or below it
	            position: 'fixed',
	            top: '0',
	            left: '0'
	        });
	    } else {                                   // apply position: static
	        $('.suggest').css({                      // if you scroll above it
	            position: 'static'
	        });
	    }

	});
</script>